/**
 * Created by TamTT on 1/13/14.
 * FPT University - Da Nang
 * Capstone project - group 3
 * Jornee
 */
$(document).ready(function(){
	function statistic_summary(){
		$.ajax({
			url: "/statistic_summary_ajax",
			type: 'POST',
			data: {},
			success: function(data) {
				if(data.status == 'error'){
					alert('Statistic summary get error! Sorry!');
					window.location.replace("/this/is/admin/page/for/admin/only/");
				} else {
					$('#dataSummary').html(data.contents);
				}
			},
			error: function() {
				alert('Statistic summary get error! Sorry!');
			}
		});
	}

	function statistic_rank(){
		$.ajax({
			url: "/statistic_rank_ajax",
			type: 'POST',
			data: {},
			success: function(data) {
				if(data.status == 'error'){
					alert('Statistic rank get error! Sorry!');
					window.location.replace("/this/is/admin/page/for/admin/only/");
				} else {
					$('#dataRank').html(data.contents);
				}
			},
			error: function() {
				alert('Statistic rank get error! Sorry!');
			}
		});
	}

	function logs(){
		$.ajax({
			url: "/logs_ajax",
			type: 'POST',
			data: {},
			beforeSend: function(){
//				$('#log_loading').html('Loading....');
			},
			success: function(data) {
				if(data.status == 'error'){
					alert('Something wrong! Sorry!');
					window.location.replace("/this/is/admin/page/for/admin/only/");
				} else {
					$('#liveLogContainer').html(data.contents);
					colorize_logs();
				}
			},
			error: function() {
				alert('Something wrong! Sorry!');
			}
		});
	}

	function colorize_logs(){
		$('.logs').each(function(index){
			var str = $(this).text();
			if(str.charAt(0) == '['){
				var manual_log = '';
				manual_log += ( '<span class=\"manual_log_date\">' + str.slice(1,40) + '</span> ' );
				if(str.charAt(42) == 'I'){
					manual_log += ( '<span class=\"manual_log_type_info\">' + str.slice(42) + '</span>' );
				} else if(str.charAt(42) == 'W'){
					manual_log += ( '<span class=\"manual_log_type_warn\">' + str.slice(42) + '</span>' );
				} else if(str.charAt(42) == 'E'){
					manual_log += ( '<span class=\"manual_log_type_err\">' + str.slice(42) + '</span>' );
				}
				$(this).html(manual_log);
			} else {
				var auto_log = '';
				auto_log += ( '<span class=\"auto_log_date\">' + str.slice(0,29) + '</span> ' );
				auto_log += ( '<span class=\"auto_log_content\">' + str.slice(30) + '</span>' );
				$(this).html(auto_log);
			}
		});
	}

	$('#liveChart').highcharts({
		chart: {
			event: {
				load: ticker()
			}
		},
		title: {
			text: 'Jornee Live Chart',
			x: -20 //center
		},
		subtitle: {
			text: 'Number of current connected user',
			x: -20
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 200,
			minRange: 5000,
			allowDecimals: false
		},
		yAxis: {
			title: {
				text: 'Number of users'
			},
			allowDecimals: false
		},
		tooltip: {
			valueSuffix: ' users'
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'middle',
			borderWidth: 0
		},
		series: [{
			name: 'Users',
			data: []
		}]
	});

	var chart = $('#liveChart').highcharts();
	var socket;

	function connect() {
		$.ajax({
			url: "/admin_token_ajax",
			type: 'POST',
			data: {},
			success: function(data) {
				if(data.status == 'error'){
					$('#status').html('Error');
				} else {
					socket = io.connect(null, { query: 'token='+data.token+'&role=admin' });
					socket.on('connect', function(){
						$('#status').html('Connected');
					});
					socket.on('disconnect', function(){
						$('#status').html('Disconnected');
					});
				}
			},
			error: function() {
				$('#status').html('Error');
			}
		});

	};

	function disconnect() {
		if(socket != null) {
			socket.disconnect();
		}
	};

	function ticker(){
		if(socket != null) {
			socket.emit('ticker', function(data) {
				if(data != 'error'){
					var d = new Date(),
						t = d.getTime(),
						point = [t,data],
						shift = chart.series[0].data.length > 10;
					chart.series[0].addPoint(point, true, shift);
				} else {
					$('#status').html('Error');
				}
			});
		}
		setTimeout(ticker, 1000);
	}

	function ultimate_search(search_str){
		$.ajax({
			url: "/ultimate_search_ajax",
			type: 'POST',
			data: { search_str: search_str },
			success: function(data) {
				if(data.status == 'error'){
					alert('Something wrong! Sorry!');
					window.location.replace("/this/is/admin/page/for/admin/only/");
				} else {
					$('#searchResult').html(data.contents);
				}
			},
			error: function() {
				alert('Something wrong! Sorry!');
			}
		});
	}

	function ultimate_user_summary(user_id){
		$.ajax({
			url: "/ultimate_user_summary_ajax",
			type: 'POST',
			data: { user_id: user_id },
			success: function(data) {
				if(data.status == 'error'){
					alert('Something wrong! Sorry!');
					window.location.replace("/this/is/admin/page/for/admin/only/");
				} else {
					$('#userDataSummary').html(data.contents);
				}
			},
			error: function() {
				alert('Something wrong! Sorry!');
			}
		});
	}

	statistic_summary();
	statistic_rank();
	$("#mainContainer").animate({ left: '9%' }, '1000');

	$('#firstTab').click(function(){
		statistic_summary();
		statistic_rank();
		$("#mainContainer").animate({ left: '9%' }, '1000');
	});

	$('#secondTab').click(function(){
		$("#mainContainer").animate({ left: '-91%' }, '1000');
		connect();
	});

	$('#thirdTab').click(function(){
		logs();
		$("#mainContainer").animate({ left: '-190%' }, '1000');
	});

	$('#fourthTab').click(function(){
		$("#mainContainer").animate({ left: '-290%' }, '1000');
	});

	$('#queryBox').keyup(function(){
		ultimate_search($('#queryBox').val());
	});

	$( "body" ).delegate( ".user", "click", function() {
		ultimate_user_summary($(this).children(".userName").text());
	});
});